<template>
  <div>
    <textarea ref="textarea"></textarea>
    <div ref="content">
      <table border="1">
        <tr>
          <td>asdf</td>
          <td style="color: red; font-size: 28px">asdf</td>
          <td>asdf</td>
          <td>
            <img
              ref="images"
              alt="Vue logo"
              src=""
            />
          </td>
        </tr>
      </table>
    </div>
    <el-button @click="cmd(0)">复制textarea</el-button>
    <el-button @click="cmd(1)">复制表格</el-button>
    <el-button @click="cmd(2)">复制远程图片</el-button>
    <el-button @click="cmd(3)">复制Base64图片</el-button>
    <el-button @click="cmd(4)">复合复制表格+Base64</el-button>
    <el-button @click="cmd(5)">复合复制表格+远程</el-button>

    <div ref="paste-content"></div>
  </div>
</template>

<script>
const ClipboardItem = window.ClipboardItem;
export default {
  methods: {
    cmd(t) {
      // let article =
      // "<h1>你好，这是H1</h1><p style='color:red'>这是段落主体内容,<b>这里是加粗</b></p>";

      let article = this.$refs.content.innerHTML;
      if (t == 0) {
        this.$refs.textarea.select();
        document.execCommand("copy");
      } else if (t == 1) {
        let copyHandler = this.copy(article);

        // 方式一
        document.addEventListener("copy", copyHandler);
        document.execCommand("copy");
        removeEventListener("copy", copyHandler);
      }
      // 方式二
      else if (t == 2) {
        this.copy2(article);
      } else if (t == 3) {
        this.copy3();
      } else if (t == 4) {
        this.copy4(article);
      } else {
        this.copy5(article);
      }
    },
    copy(article) {
      return function (event) {
        // event.clipboardData.setData("Text", "article"); //设置格式text/html
        event.clipboardData.setData("text/html", article); //设置格式text/html
        // event.clipboardData.setData("image/png", article); //设置格式text/html

        event.preventDefault();
      };
    },
    copy2() {
      this.writeClipImg(this.$refs.images.getAttribute("src"));
    },
    copy3() {
      let img = this.$refs.images;
      let base64 = this.imageBase64(img);

      let blob = this.base64ToBlob(
        base64.replace("data:image/png;base64,", ""),
        "image/png"
      );
      navigator.clipboard.write([
        new ClipboardItem({
          "image/png": blob,
        }),
      ]);
    },
    async copy4(article) {
      const text = new Blob([article], { type: "text/html" });
      let base64 = this.imageBase64(this.$refs.images);
      let image = this.base64ToBlob(
        base64.replace("data:image/png;base64,", ""),
        "image/png"
      );

      const item = new ClipboardItem({
        "image/png": image,
        "text/html": text,
      });

      try {
        await navigator.clipboard.write([item]);
        console.log("Fetched image copied.");
      } catch (err) {
        console.error(err.name, err.message);
      }
    },
    async copy5(article) {
      const text = new Blob([article], { type: "text/html" });
      const imgURL = "http://localhost:8080/img/logo.82b9c7a5.png";
      const data = await fetch(imgURL);
      const blob = await data.blob();

      const item = new ClipboardItem({
        "text/html": text,
        [blob.type]: blob,
      });

      try {
        await navigator.clipboard.write([item]);
        console.log("Fetched image copied.");
      } catch (err) {
        console.error(err.name, err.message);
      }
    },
    async writeClipImg(imgSrc) {
      console.log(imgSrc)
      try {
        const imgURL = "http://localhost:8080/img/logo.82b9c7a5.png";
        const data = await fetch(imgURL);
        const blob = await data.blob();
        console.log("blob", blob);

        await navigator.clipboard.write([
          new ClipboardItem({
            [blob.type]: blob,
          }),
        ]);
        console.log("Fetched image copied.");
      } catch (err) {
        console.error(err.name, err.message);
      }
    },
    async dataURLtoBlob(dataurl) {
      var arr = dataurl.split(",");
      //注意base64的最后面中括号和引号是不转译的
      var _arr = arr[1].substring(0, arr[1].length - 2);
      var mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    },
    imageBase64(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var dataURL = canvas.toDataURL("image/png");
      return dataURL;
    },
    // 再转成blod // 注意base64里面的特殊符号 在atob的时候不能识别“,”
    base64ToBlob(b64Data, contentType, sliceSize) {
      contentType = contentType || "";
      sliceSize = sliceSize || 512;
      var byteCharacters = window.atob(b64Data);
      // var byteCharacters  = b64Data;
      //该atob函数将base64编码的字符串解码为一个新字符串，其中包含二进制数据每个字节的字符。
      var byteArrays = [];
      for (
        var offset = 0;
        offset < byteCharacters.length;
        offset += sliceSize
      ) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);
        var byteNumbers = new Array(slice.length);
        //通过使用.charCodeAt字符串中每个字符的方法应用它来创建一个字节值数组。
        for (var i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i);
        }
        //将此字节值数组转换为实际类型的字节数组，方法是将其传递给Uint8Array构造函数。
        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
      }
      console.log(byteArrays);
      //创建一个blob：包含此数据的URL，并将其显示给用户。
      var blob = new Blob(byteArrays, { type: contentType });
      return blob;
    },
  },
  mounted() {
    let div = this.$refs["paste-content"];
    document.body.addEventListener("paste", function (event) {
      var data = (event.clipboardData && event.clipboardData.items) || [];
      console.log(data);
      for (var i = 0; i < data.length; i += 1) {
        if (data[i].kind == "string" && data[i].type.match("^text/plain")) {
          // This item is the target node
          console.log("... Drop:plain");
        } else if (
          data[i].kind == "string" &&
          data[i].type.match("^text/html")
        ) {
          // Drag data item is HTML
          data[i].getAsString(function (s) {
            div.innerHTML = s;
          });
          console.log("... Drop: HTML");
        } else if (
          data[i].kind == "string" &&
          data[i].type.match("^text/uri-list")
        ) {
          // Drag data item is URI
          console.log("... Drop: URI");
        } else if (data[i].kind == "file" && data[i].type.match("^image/")) {
          // Drag data item is an image file
          console.log("... Drop: File ");
        }
      }
    });
  },
};
</script>